package com.qicheng.wlhyspider.anhui.service;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qicheng.wlhyspider.anhui.controller.dto.AhShippingDTO;
import com.qicheng.wlhyspider.anhui.dao.AhShippingMasterRepository;
import com.qicheng.wlhyspider.anhui.dao.AhShippingNoteDriversRepository;
import com.qicheng.wlhyspider.anhui.dao.AhShippingNoteGoodsRepository;
import com.qicheng.wlhyspider.anhui.entity.AhShippingMasterEntity;
import com.qicheng.wlhyspider.anhui.entity.AhShippingNoteDriversEntity;
import com.qicheng.wlhyspider.anhui.entity.AhShippingNoteGoodsEntity;
import com.qicheng.wlhyspider.common.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * 安徽运单
 */
@Service
@Slf4j
public class AhShippingService {
    private final AhShippingMasterRepository ahShippingMasterRepository;
    private final AhShippingNoteDriversRepository ahShippingNoteDriversRepository;
    private final AhShippingNoteGoodsRepository ahShippingNoteGoodsRepository;
    private final RedisUtils redisUtils;

    public AhShippingService(AhShippingMasterRepository ahShippingMasterRepository, AhShippingNoteDriversRepository ahShippingNoteDriversRepository, AhShippingNoteGoodsRepository ahShippingNoteGoodsRepository, RedisUtils redisUtils) {
        this.ahShippingMasterRepository = ahShippingMasterRepository;
        this.ahShippingNoteDriversRepository = ahShippingNoteDriversRepository;
        this.ahShippingNoteGoodsRepository = ahShippingNoteGoodsRepository;
        this.redisUtils = redisUtils;
    }

    public Result saveAll(Integer page, String startDate, String endDate, String companyId) {
        String url = String.format("https://wlhy.ahyg.com.cn/business/shipping/list?page=%s&limit=%s&sendToProDateTimeRange3=%s+~+%s",
                page, 10000, startDate, endDate);
        Object o = redisUtils.get(Constants.AH_TOKEN);
        HttpResponse httpResponse = HttpUtil.createGet(url)
                .header("x-auth-token", o + "")
                .execute();
        if (httpResponse.getStatus() == 200) {
            String body = httpResponse.body();
            PageResult pageResult = JSONObject.parseObject(JSONObject.toJSONString(JSONObject.parse(body)), PageResult.class);
            PageResult.ResultDTO result = pageResult.getResult();
            List<AhShippingMasterEntity> list = JSONArray.parseArray(JSONArray.toJSONString(result.getRecords()), AhShippingMasterEntity.class);
            list = list.stream().peek(i -> {
                i.setIsDetail(0);
                i.setCompanyId(companyId);
            }).collect(Collectors.toList());
            ahShippingMasterRepository.saveAll(list);


            log.info(String.format("运单查询，%s到%s，第%s页，总页数%s", startDate, endDate, page, result.getPages()));
            if (page < result.getPages()) {
                page++;
                return saveAll(page, startDate, endDate, companyId);
            }

        } else if (httpResponse.getStatus() == 203) {
            log.info("登录信息失效");
//            return "返回：登录信息失效";
//            LoginUtils.login();
//             return saveAll(page, startDate, endDate,companyId);
            return Results.error("登录信息失效");
        } else {
            log.info("查询失败");
            // return "返回：查询失败";
            return Results.error("查询失败");
        }
        log.info("返回：插入成功");
        return Results.success();
    }

    public Result saveDetail(String companyId) {
        List<AhShippingMasterEntity> list = ahShippingMasterRepository.findAllByIsDetailNotAndCompanyId(1, companyId);
        if (CollectionUtils.isNotEmpty(list)) {
            List<CompletableFuture<Void>> futureList = new ArrayList<>();
            List<List<AhShippingMasterEntity>> lists = ListUtil.splitAvg(list, 32);
            for (List<AhShippingMasterEntity> items : lists) {
                CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                    for (AhShippingMasterEntity item : items) {
                        Object o = redisUtils.get(Constants.AH_TOKEN);
                        HttpResponse httpResponse = HttpUtil.createGet("https://wlhy.ahyg.com.cn/business/shipping/id?id=" + item.getId() + "&_=" + System.currentTimeMillis())
                                .header("x-auth-token", o + "")
                                .execute();
                        if (httpResponse.getStatus() == 200) {
                            String body = httpResponse.body();
                            if (StringUtils.isNotBlank(body)) {
                                Result result = JSONObject.parseObject(JSONObject.toJSONString(JSONObject.parse(body)), Result.class);

                                AhShippingDTO resultObj = JSONObject.parseObject(JSONObject.toJSONString(result.getResult()), AhShippingDTO.class);
                                AhShippingMasterEntity shippingNoteMaster = resultObj.getShippingNoteMaster();
                                List<AhShippingNoteDriversEntity> shippingNoteDrivers = resultObj.getShippingNoteDrivers();
                                List<AhShippingNoteGoodsEntity> shippingNoteGoods = resultObj.getShippingNoteGoods();
                                try {
                                    this.updateDetail(companyId, shippingNoteMaster, shippingNoteDrivers, shippingNoteGoods);
                                } catch (Exception e) {
                                    log.error(e.getMessage(), e);
                                }
                            } else if (httpResponse.getStatus() == 203) {
                                log.info("登录信息失效");
                                throw new RuntimeException("登录信息失效");

                            } else {
                                log.info("查询失败");
                                throw new RuntimeException("查询失败");
                            }
                        }
                    }
                });
                futureList.add(future);
            }
            try {
                CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0])).get();
                return Results.success();
            } catch (InterruptedException | ExecutionException e) {
                log.error(e.getMessage(), e);
                return Results.error("查询失败:" + e.getMessage());
            }
        }

        return Results.error("查询失败");
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateDetail(String companyId, AhShippingMasterEntity shippingNoteMaster, List<AhShippingNoteDriversEntity> shippingNoteDrivers, List<AhShippingNoteGoodsEntity> shippingNoteGoods) {
        shippingNoteMaster.setIsDetail(1);
        shippingNoteMaster.setCompanyId(companyId);
        shippingNoteMaster = ahShippingMasterRepository.save(shippingNoteMaster);
        for (AhShippingNoteDriversEntity shippingNoteDriver : shippingNoteDrivers) {
            shippingNoteDriver.setCompanyId(companyId);
            shippingNoteDriver.setShippingNoteMasterId(shippingNoteMaster.getId());
        }

        for (AhShippingNoteGoodsEntity shippingNoteGood : shippingNoteGoods) {
            shippingNoteGood.setCompanyId(companyId);
            shippingNoteGood.setShippingNoteMasterId(shippingNoteMaster.getId());
        }

        ahShippingNoteDriversRepository.saveAll(shippingNoteDrivers);
        ahShippingNoteGoodsRepository.saveAll(shippingNoteGoods);
    }
}
